package com.taptech.doufu.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Process;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.openapi.IWBAPI;
import com.sina.weibo.sdk.openapi.SdkListener;
import com.sina.weibo.sdk.openapi.WBAPIFactory;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.event.EventBusBindPhone;
import com.taptech.doufu.manager.TFSDKManager;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.personalcenter.PersonalInfoService;
import com.taptech.doufu.services.personalcenter.WeiboService;
import com.taptech.doufu.umeng.push.PushManager;
import com.taptech.doufu.util.CoverageChecker;
import com.taptech.doufu.util.DeviceUtil;
import com.taptech.doufu.util.DiaoBaoPath;
import com.taptech.doufu.util.NetworkInfoUtil;
import com.taptech.doufu.util.SharedPreferenceUtil;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import androidx.multidex.MultiDex;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;


public class WeMediaApplication extends Application {

    public static Context applicationContext;
    // user your appid the key.
    public static final String APP_ID = "2882303761517244510";
    // user your appid the key.
    public static final String APP_KEY = "5951724456510";

    // 此TAG在adb logcat中检索自己所需要的信息， 只需在命令行终端输入 adb logcat | grep
    // com.xiaomi.mipushdemo
    public static final String TAG = "com.taptech.doufu";

    public static int envType = 0; // 0——代表线上环境 1——代表沙箱环境
    private static WeMediaApplication instance;
    public static boolean isNeedRefreshWeex = false;
    public String sexType="0";
    public boolean isShouldUpdate=false;
    public boolean isBookShelfReady=false;
    public boolean isDayNightMode_Night= true;//是否是黑夜模式
    private SharedPreferences dayNightPreferences ;
    @Override
    public void setTheme(int resid)
    {
        super.setTheme(android.R.style.Theme_Light_NoTitleBar);
    }

    public static WeMediaApplication getInstance()
    {
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base)
    {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        applicationContext = this;
        instance = this;
        boolean showPrivacy = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean("privacy_dialog",this,true);
        if (!showPrivacy) {
            init();
        }

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                // 移除通知
                CoverageChecker.getInstance(activity).removeNotify();
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityResumed(Activity activity) {
                // 移除通知
                CoverageChecker.getInstance(activity).removeNotify();
            }

            @Override
            public void onActivityPaused(Activity activity) {
                // 延时通知
                CoverageChecker.getInstance(activity).delayNotify(activity);
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }

    public void init() {
        if (!hasInit) {
            hasInit = true;
            TFSDKManager.getInstance().initSDK();
            initWeiboSdk();
            envType = 0;
            System.out.println("sdk init");
        }
        Fresco.initialize(this);
        initDayMode();
        try {
            PushManager.getInstance().init();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        LeakCanary.install(this);//内存泄漏检测
//        BlockCanary.install(this, new AppBlockCanaryContext()).start();
        // 选用AUTO页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        DiaoBaoPath.createRootFolder();
        UEHandler ueHandler = UEHandler.getInstances();
        ueHandler.init(this);
        //设置异常处理实例
        AccountService.getInstance().loadAccountInfo((handleType, response) -> {
            if (response.getStatus() == 0) {
                JSONArray accounts = (JSONArray) response.getData();
                AccountService.getInstance().initAccountInfo(accounts);
                PersonalInfoService.getInstance().loadFans("", null);
                PersonalInfoService.getInstance().loadAttentions("", null);
                PersonalInfoService.getInstance().loadUnreadMessages();
                PushManager.getInstance().addAlias();
                EventBus.getDefault().post(new EventBusBindPhone());
            }
        });
        NetworkInfoUtil.appCon = this;
        Constant.mScreenType = DeviceUtil.getDeviceTypeAccordingScreen(getApplicationContext());
        switch (Constant.mScreenType) {
            case Constant.ScreenSplashType.DEVICE_ANDROID_LDPI:
                Constant.mMaxThumbnailWidth = Constant.mMaxThumbnailHeight = 80;
                break;

            case Constant.ScreenSplashType.DEVICE_ANDROID_MDPI:
                Constant.mMaxThumbnailWidth = Constant.mMaxThumbnailHeight = 120;
                break;

            case Constant.ScreenSplashType.DEVICE_ANDROID_HDPI:
                Constant.mMaxThumbnailWidth = Constant.mMaxThumbnailHeight = 160;
                break;

            case Constant.ScreenSplashType.DEVICE_ANDROID_XDPI:
                Constant.mMaxThumbnailWidth = Constant.mMaxThumbnailHeight = 200;
                break;
        }
    }

    private IWBAPI mWBAPI;
    private void initWeiboSdk() {
        AuthInfo authInfo = new AuthInfo(this, Constant.APP_KEY, Constant.REDIRECT_URL, WeiboService.SCOPE);
        mWBAPI = WBAPIFactory.createWBAPI(this);
        mWBAPI.registerApp(this, authInfo, new SdkListener() {
            @Override
            public void onInitSuccess() {
                // SDK初始化成功回调，成功⼀次后再次初始化将不再有任何回调
            }

            @Override
            public void onInitFailure(Exception e) {
                // SDK初始化失败回调
            }
        });
    }



    private boolean hasInit = false;
    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        for (RunningAppProcessInfo info : processInfos)
        {
            if (info.pid == myPid && mainProcessName.equals(info.processName))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 初始化黑夜模式数据
     */
    public void initDayMode(){

        if(dayNightPreferences == null){
            dayNightPreferences= SharedPreferenceUtil.dayNightPreferences(this);
        }

        if(dayNightPreferences.getBoolean(Constant.DayNight.IS_NIGHT, false)){
            isDayNightMode_Night = true ;
        }else {
            isDayNightMode_Night = false;
        }
    }
    /**
     * 保存黑夜模式
     */
    public void saveDayMode( ){
        isDayNightMode_Night = !isDayNightMode_Night;
        if(dayNightPreferences == null){
            dayNightPreferences= SharedPreferenceUtil.dayNightPreferences(this);
        }
        dayNightPreferences.edit().putBoolean(Constant.DayNight.IS_NIGHT ,isDayNightMode_Night).commit();

    }

}
